<?php

namespace frontend\models;

use Yii;
use common\base\Model;

/**
 * ContactForm is the model behind the contact form.
 */
class BindMobileForm extends Model {

    public $mobile;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['mobile'], 'required'],
        ];
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     *
     * @param string $email the target email address
     * @return bool whether the email was sent
     */
    public function bind() {
        if (!$this->validate()) {
            $this->dumpError('提交失败');
        }

        /* @var $security \common\base\Security */
        $security = Yii::$app->security;
        $mobileUser = User::findOne(['mobile' => $security->generatePrivateKey($this->mobile)]);
        if ($mobileUser) {
            $this->dumpError('该手机号已被绑定,不能重复绑定!');
        }

        $user = User::findOne($this->getUser()->getId());
        $user->setMobile($this->mobile);

        if (!$user->save()) {
            $this->dumpError('更绑手机号失败!', $user->getFirstErrors());
        }

        return $user;
    }

}
